// pages/sys/upgoods/upgoods.js

const db = wx.cloud.database()
const util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploaderList: [],
    uploaderNum:0,
    showUpload:true,
    img:"",
    items: [
      
    ],
    fruit: [{
      id: 1,
      name: '热销推荐',
  },  {
      id: 3,
      name: '今日特价'
  }, {
    id: 4,
    name: '不显示到首页'
}],
    current: '',
    fenleichecked:"",
    goodsname:"",//商品名
    minprice:"",//现价
    originalPrice:"",//原价
    brand:"",//品牌
    specifications:"",//规格
    qualityGuaranteePeriod:"",//保质期
    storageMode:"",//存储方式
    pic:"",//小图
    pics:[],//主页轮播图数组
    limitedPurchase:"",//限购策略
    categoryId:"",//分类
    content:"",//描述
    stores:"",//库存数
    banner:"",//为1 显示到首页轮播图
    tejia:"",//为1 显示到首页特价
    recommendStatus:"",//为1 显示到推荐精品
    id1:null,
    goodsUpdate:{}
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let  that = this;
  
    that.setData({
      id1:options.id
    })
    //加载分类
    const db = wx.cloud.database()
    db.collection('categories').orderBy('paixu','asc').get({
      success: (res) => {
        var fenlei =[];
        for (let index = 0; index < res.data.length; index++) {
          const element =  res.data[index];
          fenlei.push({value:element._id,title:element.name})
        }
        that.setData({
          items:fenlei
        })
        //加载商品
        that.getgoods()
      }

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //根据id查商品
  getgoods(){
    let  that = this;
    db.collection('goods').where({
      _id: that.data.id1
    }).get({
      success: res => {
        console.log(res)
        that.setData({
          goodsUpdate:res.data[0],
          uploaderList:res.data[0].pics,
          uploaderNum:res.data[0].pics.length,
          goodsname:res.data[0].name,
          minprice:res.data[0].minPrice,
          originalPrice:res.data[0].originalPrice,
          brand:res.data[0].brand,
          specifications:res.data[0].specifications,//规格
          qualityGuaranteePeriod:res.data[0].qualityGuaranteePeriod,//保质期
          storageMode:res.data[0].storageMode,//存储方式
          pic:res.data[0].pic,//小图
          pics:res.data[0].pics,//主页轮播图数组
          limitedPurchase:res.data[0].limitedPurchase,//限购策略
          categoryId:res.data[0].categoryId,//分类
          content:res.data[0].content,//描述
          stores:res.data[0].stores,//库存数
        })
        if(res.data[0].tejia ==1){
          that.setData({
            current:"今日特价",
            tejia:1
          })
        }
        
        if(res.data[0].recommendStatus ==1){
          that.setData({
            current:"精品推荐",
            recommendStatus:1
          })
        }
        //
        for (let index = 0; index < that.data.items.length; index++) {
          const element = that.data.items[index];
          if(element.value ==  res.data[0].categoryId){
            that.setData({
              fenleichecked:element.value
            })
            
          }
        }
        //
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton()
   
  },
  //选择显示到首页
  handleFruitChange({ detail = {} }) {
    
    if(detail.value =="轮播图"){
      this.setData({
        banner: 1,//设置商品显示到首页
        tejia: "",
        recommendStatus: "",
      });
    }else
    if(detail.value =="今日特价"){
      this.setData({
        banner: "",
        tejia: 1,//设置商品显示到首页
        recommendStatus: "",
      });
    }else
    if(detail.value =="精品推荐"){
      this.setData({
        banner: "",
        tejia: "",//设置商品显示到首页
        recommendStatus: 1,//设置商品显示到首页
      });
    }
    this.setData({
        current: detail.value,
    });
},

  clearImg:function(e){
    var nowList = [];//新数据
    var uploaderList = this.data.uploaderList;//原数据
    
    for (let i = 0; i < uploaderList.length;i++){
        if (i == e.currentTarget.dataset.index){
            continue;
        }else{
            nowList.push(uploaderList[i])
        }
    }
    this.setData({
        uploaderNum: this.data.uploaderNum - 1,
        uploaderList: nowList,
        showUpload: true
    })
  },
  //展示图片
  showImg:function(e){
      var that=this;
      wx.previewImage({
          urls: that.data.uploaderList,
          current: that.data.uploaderList[e.currentTarget.dataset.index]
      })
  },
  //上传图片
  upload: function(e) {
      var that = this;
      wx.chooseImage({
          count: 9 - that.data.uploaderNum, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: chooseResult => {
              console.log(chooseResult)
              wx.cloud.uploadFile({
                  // 指定上传到的云路径
                  cloudPath: (new Date()).valueOf()+'.png', // 文件名
                  // 指定要上传的文件的小程序临时文件路径
                  filePath: chooseResult.tempFilePaths[0],
                  // 成功回调
                  success: res => {
                    console.log('上传成功', res)
                    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                    let tempFilePaths = res.fileID;
                  
                    wx.cloud.getTempFileURL({
                      fileList:[{
                          fileID:tempFilePaths,
                          maxAge:60*60


                      }]
                    }).then((res)=>{
                      console.log(res.fileList)
                      console.log(that.data.img )
                      let uploaderList = that.data.uploaderList.concat(res.fileList[0].tempFileURL);
                      console.log(uploaderList.length)
                      if (uploaderList.length==9){
                        that.setData({
                            showUpload:false
                        })
                      }
                      that.setData({
                        uploaderList: uploaderList,
                        uploaderNum: uploaderList.length,
                      })
                    })
                    that.setData({
                      
                    })
                  },
                })
              
          }
      })
  },
  //选择商品分类
  onChange(e){
    
    console.log(e.detail.value);
    this.data.categoryId = e.detail.value;
    this.setData({
      categoryId: e.detail.value
    })
  },
  goodnameInput(e){
    this.data.goodsname = e.detail.value
    console.log( this.data.goodsname)
  },
  minpriceInput(e){
    this.data.minprice = e.detail.value
    console.log( this.data.minprice)
  },
  originalPriceInput(e){
    this.data.originalPrice = e.detail.value
    console.log( this.data.originalPrice)
  },
  brandInput(e){
    this.data.brand = e.detail.value
    console.log( this.data.brand)
  },
  specificationsInput(e){
    this.data.specifications = e.detail.value
    console.log( this.data.specifications)
  },
  qualityGuaranteePeriodInput(e){
    this.data.qualityGuaranteePeriod = e.detail.value
    console.log( this.data.qualityGuaranteePeriod)
  },
  storageModeInput(e){
    this.data.storageMode = e.detail.value
    console.log( this.data.storageMode)
  },
  limitedPurchaseInput(e){
    this.data.limitedPurchase = e.detail.value
    console.log( this.data.limitedPurchase)
  },
  storesInput(e){
    this.data.stores = e.detail.value
    console.log( this.data.stores)
  },
  contentInput(e){
    this.data.content = e.detail.value
    console.log( this.data.content)
  },

  //save
  save:function(e){
    
    var savestatus = ""
    if(parseInt(e.currentTarget.dataset.type) == 1){
      savestatus = 1//上架
    }else if(parseInt(e.currentTarget.dataset.type) == 2) {
      savestatus = 2//待上架
      }
    var that=this
  
    var that=this
    if(that.data.goodsname ==""){
      wx.showModal({
        title: '提示',
        content: '请输入商品名称',
      })
    }else if(that.data.minprice  =="" ){
      wx.showModal({
        title: '提示',
        content: '请输入现价',
      })
    }else if(that.data.originalPrice  =="" ){
      wx.showModal({
        title: '提示',
        content: '请输入原价',
      })
    }else if(that.data.stores  =="" ){
      wx.showModal({
        title: '提示',
        content: '请输入库存量',
      })
    }
    
    else if(that.data.uploaderNum  ==0){
      wx.showModal({
        title: '提示',
        content: '请上传图片',
      })
    }
    else{
        db.collection('goods').doc(that.data.id1).update({
        data: {
          name:that.data.goodsname,//商品名
          minPrice:parseFloat(that.data.minprice),//现价
          originalPrice:parseFloat(that.data.originalPrice),//原价
          brand:that.data.brand,//品牌
          specifications:that.data.specifications,//规格
          qualityGuaranteePeriod:that.data.qualityGuaranteePeriod,//保质期
          storageMode:that.data.storageMode,//存储方式
          pic:that.data.uploaderList[0],//小图
          pics:that.data.uploaderList,//主页轮播图数组
          limitedPurchase:that.data.limitedPurchase,//限购策略
          categoryId:that.data.categoryId,//分类
          content:that.data.content,//描述
          stores:parseInt(that.data.stores),//库存数
          banner:parseInt(that.data.banner),//为1 显示到首页轮播图
          tejia:parseInt(that.data.tejia),//为1 显示到首页特价
          recommendStatus:parseInt(that.data.recommendStatus),//为1 显示到推荐精品
          dateAdd:util.formatTime(new Date()),
          status:savestatus
        },
        success: res => {
          /// 在返回结果中会包含新创建的记录的 _id
          console.log(res)
          wx.showToast({
            title: '修改商品成功',
          })
        wx.navigateBack({
          delta: 1,
        })
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '修改商品失败'
          })
          console.error('[数据库] [新增记录] 失败：', err)
        }
      })
    }
  },
  toCategories(){
    wx.navigateTo({
      url: '../categories/categories',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})